//
//  TableEnableProtocol.swift
//  CooperSwift
//
//  Created by 计海峰 on 2021/4/27.
//  Copyright © 2021 CooperSwift. All rights reserved.
//

import Foundation
//import WCDBSwift
import CooperSwift

// https://www.jianshu.com/p/c419c0a8edeb

public extension TableDecodableBase {
    
    static func tableName() -> String {
        return "t_\(String(cString: object_getClassName(self)).split(separator: ".").last!.lowercased())"
    }
    
    func tableName() -> String {
        return "t_\(String(cString: object_getClassName(self)).split(separator: ".").last!.lowercased())"
    }
    
}


class WcdbManger {
    
    static let shared = WcdbManger()
    
    private init() {}
    
    /// 本地数据库
    public var db : Database? = {
            // 创建数据库
            let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let database = Database(withPath: docPath + "/CooperSwift_wcdb.db")
            log.debug(docPath)
            return database
        }()
  
    
    /// 创建表
    func createTable<T: TableDecodable>(tableName: String, modelType: T.Type) -> Bool {
        guard WcdbManger.shared.db != nil else { return false}
        do {
            try db?.create(table: tableName, of: modelType)
            return true
        } catch {
            log.error(error)
            return false
        }
    }
    
    
    func createTable<T: TableDecodable>(modelType: T.Type) -> Bool {
        return createTable(tableName: modelType.tableName() , modelType: modelType)
    }
    
    /// 插入数据
    public func insert<T: TableEncodable>(objects:[T], intoTable tableName: String) -> Bool {
        do {
//            try db?.insert(objects: objects, intoTable: tableName)
            try db?.insertOrReplace(objects: objects, intoTable: tableName)
            return true
        }catch {
            log.error(error)
            return false
        }
    }
    
    /// 只能是同类型
    public func insert<T: TableEncodable>(objects:[T]) -> Bool {
        if objects.count <= 0 || !(objects.first is TableDecodableBase) {
            return false
        }
        return insert(objects: objects, intoTable: (objects.first as! TableDecodableBase).tableName())
    }
    
    /// 删除  .Properties.id >
    func delete(fromTable: String, where condition: Condition? = nil) -> Bool {
        do {
            try db?.delete(fromTable: fromTable, where:condition)
            return true
        } catch {
            log.error(error)
            return false
        }
    }
    
    /// 查询
    func qurey<T: TableDecodable>(fromTable: String, cls cName: T.Type, where condition: Condition? = nil, orderBy orderList:[OrderBy]? = nil) -> [T]? {
        do {
            let allObjects: [T] = try (db?.getObjects(fromTable: fromTable, where:condition, orderBy:orderList))!
            debugPrint("\(allObjects)");
            return allObjects
        } catch let error {
            log.error("no data find \(error.localizedDescription)")
        }
        return nil
    }
    
    /// 修改
    public func update<T: TableEncodable>(fromTable table: String, on propertys:[PropertyConvertible], itemModel object:T,where condition: Condition? = nil) {
        do {
            try db?.update(table: table, on: propertys, with: object, where: condition)
        } catch let error {
            debugPrint(" update obj error \(error.localizedDescription)")
        }
    }
    
    /// 删除数据表
    func dropTable(table: String) -> Bool {
        do {
            try db?.drop(table: table)
            return true
        } catch let error {
            log.error(error)
            return false
        }
    }
    
    /// 删除所有与该数据库相关的文件
    func removeDbFile() -> Void {
        do {
            try db?.close(onClosed: {
                try db?.removeFiles()
            })
        } catch let error {
            debugPrint("not close db \(error)")
        }
        
    }
   
    
}
